package com.op.teachingliteapp.fragment.courseDiscussion.sonCourseDiscussion;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.op.teachingliteapp.R;
import com.op.teachingliteapp.activity.CourseActivity;
import com.op.teachingliteapp.bean.SeminarBean;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.teachinglite.SeminarsUrl;
import com.op.teachingliteapp.database.dao.SeminarDao;
import com.op.teachingliteapp.util.ScreenSendUtils;
import com.op.teachingliteapp.util.StringUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;

public class sonSeminarFragment extends Fragment {
	private final static String TAG = sonSeminarFragment.class.getSimpleName();
	private sonSeminarAdapter madapter;
	private ArrayList<sonSeminarData> moreList = new ArrayList<sonSeminarData>();
	private View root;
	private String getuserId, getCourseId;
	private SharedPreferences preferences;
	private EditText editText;
	
	// private String getCourseUserId, getCourseId;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		final View root = inflater.inflate(R.layout.fragment_details, container, false);
		this.root = root;

		preferences = getActivity().getSharedPreferences("TeachingLite", Context.MODE_PRIVATE);
		getuserId = preferences.getString(Common.Prefs.USER_ID, "");
		getCourseId = preferences.getString(Common.Prefs.COURSE_ID, "");
		downLoadData();
		setReplyComments(root);
		ListView listView = (ListView) root.findViewById(R.id.morelistview);
		madapter = new sonSeminarAdapter(getActivity(), moreList);
		listView.setAdapter(madapter);
		listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == SCROLL_STATE_IDLE) {
					ScreenSendUtils.send(root);
					
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

			}
		});

		return root;

	}

	// *********************************回复评论*******************************************************

	public void setReplyComments(View root) {
		editText = (EditText) root.findViewById(R.id.user_in);
		Button sendppost = (Button) root.findViewById(R.id.sendppost);
		sendppost.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String Content = editText.getText().toString();
				editText.setText(null);
				hideKey();
				sendToOnlineData("", Content, getCourseId);
			}
		});
	}
	public void hideKey() {
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}
	/**
	 * 发送字符串到网上数据库 Title,Content,userId,courseId，parentId 依次是标题，内容，课程id
	 */
	public void sendToOnlineData(String title, String Content, String courseId) {
		SharedPreferences preferences = getActivity().getSharedPreferences("TeachingLite", Context.MODE_PRIVATE);
		String getUserId = preferences.getString(Common.Prefs.USER_ID, "");// 用户id
		String getSeminarId = preferences.getString(Common.Prefs.SEMINAR_ID, "");// 用户id
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Common.Seminar.ADD_UPDATE_SEMINAR_CONTENT, Content));
		params.add(new BasicNameValuePair(Common.Seminar.ADD_UPDATE_SEMINAR_USER_ID, getUserId));
		params.add(new BasicNameValuePair(Common.Seminar.ADD_UPDATE_SEMINAR_TITLE, title));
		params.add(new BasicNameValuePair(Common.Seminar.ADD_UPDATE_SEMINAR_COURSE_ID, courseId));
		params.add(new BasicNameValuePair(Common.Seminar.ADD_UPDATE_SEMINAR_PARENT_ID, getSeminarId));

		HttpPostTask task = new HttpPostTask(getActivity(), SeminarsUrl.ADD_SEMINAR, params);
		task.setTaskListener(new OnTaskProcessListener() {

			@Override
			public void prepare() {
				// TODO Auto-generated method stub

			}

			@Override
			public void completed(String result) {
				// ToastUtils.show(getActivity(), "发布帖子成功");
				downLoadData();
				madapter.notifyDataSetChanged();
                ScreenSendUtils.sendWithDely(root);
			}
		});
		task.execute();
	}

	// *********************************回复评论*******************************************************

	// ***********************************************获取子贴内容**********************************************

	/**
	 * 从数据库获取数据 // 从数据库提取课程讨论主贴内容
	 */
	public void getDataFromDatabase() {
		SeminarDao seminarDao = new SeminarDao(getActivity(), getuserId);
		List<SeminarBean> seminar = seminarDao.getSeminarByCourseId(getCourseId);
		moreList.clear();
		// 获取讨论标题
		int l = seminar.size()-1;
		for (int i = 0; i < seminar.size(); i++) {
			String title = seminar.get(i).getTitle();
			String time = seminar.get(i).getCreateTime();
			String context = seminar.get(i).getContent();
			String name = seminar.get(i).getUserBean().getName();
			String avatar = seminar.get(i).getUserBean().getImageUrl();
			String like = seminar.get(i).getLikeCount();// 点赞
			String ChildCount = seminar.get(i).getChildCount();// 评论数
			String image = seminar.get(i).getImageUrl();
			String userId = seminar.get(i).getUserBean().getId();
			String seminarId = seminar.get(i).getId();
			String seminarParentId = seminar.get(i).getParentId();
			String Pircture = seminar.get(i).getImageUrl();
			Log.i(TAG, "userId " + userId);
			Log.i(TAG, "头像 " + avatar);
			Log.i(TAG, "点赞数 " + like);
			Log.i(TAG, "评论数" + ChildCount);
			Log.i(TAG, "图片" + image);
			Log.i(TAG, "*****************seminarId*******************" + seminarId);
			if (seminarParentId.equals("null")) {
				/*
				 * 楼主的构造方法 名字 ，头像，时间，标题，内容，图片 ,用户id
				 */
				moreList.add(new sonSeminarData(name, avatar, time, title, context, Pircture, userId, seminarId,"楼主"));
				Log.i(TAG, "楼主:" + userId);
			} else {
				/*
				 * 这是回复楼主的评论名字，头像 ，时间，回复内容
				 */
				moreList.add(new sonSeminarData(name, avatar, time, context, userId, seminarId,l+"楼"));
				l=l-1;
				Log.i(TAG, "跟帖:" + userId);
			}
		}
		Collections.reverse(moreList); // 倒序
	}

	/**
	 * 从网上下拉json，解析，存入数据库再提取
	 */
	public void downLoadData() {
		final String getSeminarId = preferences.getString(Common.Prefs.SEMINAR_ID, "");

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Common.Prefs.PARENT_ID, getSeminarId));
		HttpPostTask task = new HttpPostTask(getActivity(), SeminarsUrl.GET_ROOT_AND_CHILD_SEMINARS_BY_PARENT_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				if (StringUtils.isEmptyOrStringNull(result)) {
					getDataFromDatabase();
				} else {
					Log.i(TAG, "解析" + result);
					// 有网络登陆时
					analyticalSeminar(result);
					getDataFromDatabase();
				}
				madapter.notifyDataSetChanged();
				// 这是用来传屏的。数据更新完就调这句话
				ScreenSendUtils.sendWithDely(root);

			}

		});
		task.execute();// 执行结束，圈转完
	}

	/**
	 * 解析主贴或子贴json，并存入数据库
	 * 
	 * @param result
	 * 
	 */
	public void analyticalSeminar(String result) {

		// 判断得到的数据是否为null
		if (!StringUtils.isEmptyOrStringNull(result)) {
			try {
				JSONObject jsonobjectresult = new JSONObject(result);
				String message = jsonobjectresult.getString("message");
				// 不存在parent，即主贴时
				if (message.equals("Success")) {
					SeminarDao seminarDao = new SeminarDao(getActivity(), getuserId);
					// 清空数据库
					seminarDao.empty();
					JSONObject resultMap = jsonobjectresult.getJSONObject("resultMap");
					JSONArray seminarList = resultMap.getJSONArray("seminarList");
					for (int i = 0; i < seminarList.length(); i++) {
						JSONObject seminar = new JSONObject();
						seminar = seminarList.getJSONObject(i);

						// 将JsonObject存入本地数据库
						SeminarBean seminarBean = new SeminarBean();
						seminarBean.fillAttributeByJson(seminar);
						seminarDao.insertOrUpdate(seminarBean);
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	// **************************************************************************************************

	@Override
	public void onResume() {
		super.onResume();

		ScreenSendUtils.sendWithDely(root);
	}
}
